import React, { useEffect, useRef, useState } from "react";
import {
  Button,
  Checkbox,
  Col,
  Form,
  Row,
  Slider,
  DatePicker,
  Modal,
  Pagination,
} from "antd";
import {
  AimOutlined,
  CloseOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import styles from "./index.module.scss";
import testImg from "@/assets/images/test.png";

import laosGeoJSON from "./laowo.json";
import jianpuzhaiGeoJSON from "./jianpuzhai.json";

import miandianGeoJSON from "./miandian.json";
import taiguoGeoJSON from "./taiguo.json";
import yuenanGeoJSON from "./yuenan.json";

export default function DataQuery() {
  const { T } = window;
  const mapRef: any = useRef(null);
  const { RangePicker } = DatePicker;
  const [formCon, setFormCon]: any = useState(false);
  const [map, setMap]: any = useState(null);
  const [mapInitialized, setMapInitialized]: any = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [dataDesc, setDataDesc]: any = useState({});

  // 地图初始化
  useEffect(() => {
    if (mapRef.current && !mapInitialized) {
      const newMap = new T.Map(mapRef.current, {
        minZoom: 3,
        maxZoom: 18,
      });
      newMap.centerAndZoom(new T.LngLat(102.0, 20.0), 4);
      const ctrl = new T.Control.MapType();
      newMap.addControl(ctrl);
      setMap(newMap);
      setMapInitialized(true);
    }
  }, []);

  // 根据国家名称添加图层
  const addCountryLayer = (countryName: any) => {
    switch (countryName) {
      case "laos": {
        // 添加老挝图层
        const laoGeometry = laosGeoJSON.geometries[0];
        const laoCoordinates = laoGeometry.coordinates[0];
        const laoPoints = laoCoordinates.map(
          (item) => new T.LngLat(item[0], item[1])
        );
        const laos = new T.Polygon(laoPoints, {
          color: "blue",
          weight: 2,
          opacity: 1,
          fillColor: "blue",
          fillOpacity: 0.2,
        });
        map.addOverLay(laos);
        break;
      }
      case "cambodia": {
        // 添加柬埔寨图层
        const jianGeometry = jianpuzhaiGeoJSON.geometries[0];
        const jianCoordinates = jianGeometry.coordinates[0];
        const jianPoints = jianCoordinates.map(
          (item) => new T.LngLat(item[0], item[1])
        );
        const cambodia = new T.Polygon(jianPoints, {
          color: "blue",
          weight: 2,
          opacity: 1,
          fillColor: "blue",
          fillOpacity: 0.2,
        });
        map.addOverLay(cambodia);
        break;
      }
      case "myanmar": {
        // 添加缅甸图层
        const mianGeometry = miandianGeoJSON.geometries[0];
        const mianCoordinates = mianGeometry.coordinates;
        const mianPolygons = mianCoordinates.map((polygonCoordinates) => {
          const lineCoordinates = polygonCoordinates[0];
          const taiPoints = lineCoordinates.map(
            (item) => new T.LngLat(item[0], item[1])
          );
          return new T.Polygon(taiPoints, {
            color: "blue",
            weight: 2,
            opacity: 1,
            fillColor: "blue",
            fillOpacity: 0.2,
          });
        });
        mianPolygons.forEach((polygon) => {
          map.addOverLay(polygon);
        });
        break;
      }
      case "thailand": {
        // 添加泰国图层
        const taiGeometry = taiguoGeoJSON.geometries[0];
        const taiCoordinates = taiGeometry.coordinates;
        const taiPolygons = taiCoordinates.map((polygonCoordinates) => {
          const lineCoordinates = polygonCoordinates[0];
          const taiPoints = lineCoordinates.map(
            (item) => new T.LngLat(item[0], item[1])
          );
          return new T.Polygon(taiPoints, {
            color: "blue",
            weight: 2,
            opacity: 1,
            fillColor: "blue",
            fillOpacity: 0.2,
          });
        });
        taiPolygons.forEach((polygon) => {
          map.addOverLay(polygon);
        });
        break;
      }
      case "vietnam": {
        // 添加越南图层
        const yueGeometry = yuenanGeoJSON.geometries[0];
        const yueCoordinates = yueGeometry.coordinates;
        const yuePolygons = yueCoordinates.map((polygonCoordinates) => {
          const lineCoordinates = polygonCoordinates[0];
          const taiPoints = lineCoordinates.map(
            (item) => new T.LngLat(item[0], item[1])
          );
          return new T.Polygon(taiPoints, {
            color: "blue",
            weight: 2,
            opacity: 1,
            fillColor: "blue",
            fillOpacity: 0.2,
          });
        });
        yuePolygons.forEach((polygon) => {
          map.addOverLay(polygon);
        });
        break;
      }
      default:
        break;
    }
  };
  // 修改国家复选框的onChange事件
  const handleCountryChange = (checkedValues: any) => {
    if (mapInitialized && map) {
      map.clearOverLays();
      checkedValues.forEach((countryName: any) => {
        addCountryLayer(countryName);
      });
    }
  };

  // 查询表单;
  const [form] = Form.useForm();
  const [satelliteData, setSatelliteData]: any = useState({
    GF1: { WFV: false, PMS: false },
    GF2: { PMS: false },
    GF3: { SAR: false },
    GF4: { PMI: false, PMS: false, IRS: false, B1: false },
    GF5: { AHSI: false, VIMS: false },
    GF6: { WFV: false, PMS: false },
    GF7: { DLC: false, BWD: false },
  });
  const handleSatelliteChange = (satellite: any, values: any) => {
    const newValues: any = {};
    Object.keys(satelliteData[satellite]).forEach((key: any) => {
      newValues[key] = values.includes(key);
    });
    setSatelliteData((prevData: any) => ({
      ...prevData,
      [satellite]: newValues,
    }));
  };
  const handleAllSatellitesChange = (e: any) => {
    const allChecked = e.target.checked;
    const newSatelliteData = Object.keys(satelliteData).reduce(
      (acc: any, sat: any) => {
        acc[sat] = Object.keys(satelliteData[sat]).reduce(
          (acc2: any, key: any) => {
            acc2[key] = allChecked;
            return acc2;
          },
          {}
        );
        return acc;
      },
      {}
    );
    setSatelliteData(newSatelliteData);
    // 设置表单字段的值
    const fieldsValue = Object.keys(newSatelliteData).reduce(
      (acc: any, sat: any) => {
        acc[sat] = allChecked ? Object.keys(newSatelliteData[sat]) : [];
        return acc;
      },
      {}
    );

    form.setFieldsValue(fieldsValue);
  };
  // 渲染卫星选项的函数
  const renderSatelliteOptions = (satellite: any) => {
    const options = Object.keys(satelliteData[satellite]).map((key) => (
      <Checkbox value={key} className={styles.checkColor} key={key}>
        {key}
      </Checkbox>
    ));
    return (
      <Form.Item
        name={satellite}
        className={styles.satellite_item}
        label={<span className={styles.title}>{satellite}</span>}
      >
        <Checkbox.Group
          value={Object.keys(satelliteData[satellite]).filter(
            (key) => satelliteData[satellite][key]
          )}
          onChange={(checkedValues) =>
            handleSatelliteChange(satellite, checkedValues)
          }
        >
          {options}
        </Checkbox.Group>
      </Form.Item>
    );
  };
  const onReset = () => {
    form.resetFields();
    map.clearOverLays();
    setSatelliteData({
      GF1: { WFV: false, PMS: false },
      GF2: { PMS: false },
      GF3: { SAR: false },
      GF4: { PMI: false, PMS: false, IRS: false, B1: false },
      GF5: { AHSI: false, VIMS: false },
      GF6: { WFV: false, PMS: false },
      GF7: { DLC: false, BWD: false },
    });
  };
  const onConfirm = () => {
    console.log(form.getFieldsValue());
    // 这里可以添加获取表单数据的逻辑
    setFormCon(true);
  };
  // 表单默认值
  const initialValues = {
    cloudAmount: 48,
    GF1: ["WFV", "PMS"],
  };
  // 查询结果数据
  const result = [
    {
      id: 1,
      cover: testImg,
      satellite: "GF6",
      sensor: "PMS",
      title: "GF6_WFV_E99.1_N48.6_20230920_L1A1420356320.tar.gz",
    },
    {
      id: 2,
      cover: testImg,
      satellite: "GF1",
      sensor: "WAV",
      title: "GF6_WFV_E99.1_N48.6_20230920_L1A1420356320.tar.gz",
    },
    {
      id: 3,
      cover: testImg,
      satellite: "ZY302",
      sensor: "NAD",
      title: "GF6_WFV_E99.1_N48.6_20230920_L1A1420356320.tar.gz",
    },
  ];

  const [page, setPage] = useState(1); //当前页码
  const total = result.length;

  const lastTodoInView = page * 3;
  const firstTodoInView = lastTodoInView - 3;

  const todosForDisplay = result.slice(firstTodoInView, lastTodoInView);
  console.log(todosForDisplay);
  const handleChange = (pageNumber: any) => {
    setPage(pageNumber);
  };

  return (
    <div>
      {/* 表单 */}
      <div className={styles.fixedBox}>
        <div className={styles.topTitle}>Image product Search</div>
        <div className={styles.formWrap}>
          <Form
            form={form}
            layout="vertical"
            className={styles.formStyle}
            initialValues={initialValues} // 设置初始值
          >
            {/* 国家选择 */}
            <Form.Item
              name="country"
              label={
                <span className={styles.formTitle}>Country selection</span>
              }
            >
              <Checkbox.Group onChange={handleCountryChange}>
                <Row>
                  <Col span={12}>
                    <Checkbox
                      value="myanmar"
                      style={{ color: "#545963", fontSize: "1px" }}
                    >
                      Myanmar
                    </Checkbox>
                  </Col>
                  <Col span={12}>
                    <Checkbox
                      value="thailand"
                      style={{ color: "#545963", fontSize: "1px" }}
                    >
                      Thailand
                    </Checkbox>
                  </Col>
                  <Col span={12}>
                    <Checkbox
                      value="laos"
                      style={{ color: "#545963", fontSize: "1px" }}
                    >
                      Laos
                    </Checkbox>
                  </Col>
                  <Col span={12}>
                    <Checkbox
                      value="vietnam"
                      style={{ color: "#545963", fontSize: "1px" }}
                    >
                      Vietnam
                    </Checkbox>
                  </Col>
                  <Col span={12}>
                    <Checkbox
                      value="cambodia"
                      style={{ color: "#545963", fontSize: "1px" }}
                    >
                      Cambodia
                    </Checkbox>
                  </Col>
                </Row>
              </Checkbox.Group>
            </Form.Item>
            {/* 采集时间 */}
            <Form.Item
              name="collectTime"
              label={<span className={styles.formTitle}>Acquisition time</span>}
            >
              <RangePicker />
            </Form.Item>
            {/* 云量 */}
            <Form.Item
              name="cloudAmount"
              label={<span className={styles.formTitle}>Cloudage</span>}
            >
              <Slider
                tooltip={{ open: true }}
                // Slider轨道的颜色
                railStyle={{ backgroundColor: "#02051b" }}
                // Slider选中部分的颜色
                trackStyle={{ backgroundColor: "#3ea0f9" }}
              />
            </Form.Item>
            {/* 卫星数据 */}
            <Form.Item>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                }}
              >
                <label className={styles.formTitle}>Satellite data</label>
                <Checkbox
                  onChange={handleAllSatellitesChange}
                  className={styles.formTitle}
                >
                  Select all
                </Checkbox>
              </div>
              {Object.keys(satelliteData).map((satellite) => (
                <React.Fragment key={satellite}>
                  {renderSatelliteOptions(satellite)}
                </React.Fragment>
              ))}
            </Form.Item>
            {/* 重置与提交 */}
            <Form.Item style={{ display: "flex", justifyContent: "flex-end" }}>
              <Button className={styles.resetBtn} onClick={onReset}>
                Reset
              </Button>
              <Button type="primary" onClick={onConfirm}>
                Confirm
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
      {/* 查询结果 */}
      {formCon && (
        <div className={styles.formConfirm}>
          <div className={styles.topTitle}>
            Search result
            <CloseOutlined
              onClick={() => {
                setFormCon(false);
              }}
              style={{ marginLeft: "160px" }}
            />
          </div>
          <div className={styles.formStyle}>
            {/* 数据 */}
            <div style={{ padding: "10px" }}>Total 3 pieces of data</div>
            {result.map((item: any) => {
              return (
                <div className={styles.dataItem} key={item.id}>
                  {/* 拇指图 */}
                  <div>
                    <img src={item.cover} />
                  </div>
                  <div>
                    {/* 上方 */}
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                      }}
                    >
                      {/* 左边标签 */}
                      <div
                        style={{
                          display: "flex",
                          justifyContent: "space-between",
                        }}
                      >
                        <div
                          className={styles.labels}
                          style={{ marginRight: "5px" }}
                        >
                          {item.satellite}
                        </div>
                        <div className={styles.labels}>{item.sensor}</div>
                      </div>
                      {/* 右边图标 */}
                      <div>
                        <AimOutlined
                          style={{ marginRight: "8px ", fontSize: "12px" }}
                        />
                        <a
                          href="https://www.cpeos.org.cn/dataSearch3D/#/standardProduct"
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          <DownloadOutlined
                            style={{
                              fontSize: "12px",
                              cursor: "pointer",
                              color: "#3fa0fe",
                            }}
                          />
                        </a>
                      </div>
                    </div>
                    {/* 下方 */}
                    <div
                      className={styles.navTitle}
                      onClick={() => {
                        setDataDesc(item);
                        setIsModalOpen(true);
                      }}
                    >
                      {item.title}
                    </div>
                  </div>
                </div>
              );
            })}
            <Pagination
              style={{ margin: "20px 0" }}
              defaultCurrent={1}
              current={page} //当前页码
              total={total} //总页数
              pageSize={3} //存储每页上的项目数
              onChange={handleChange}
            />
          </div>
        </div>
      )}
      {/* 查询结果 */}
      <Modal
        title="数据集信息"
        open={isModalOpen}
        footer={null}
        onCancel={() => {
          setIsModalOpen(false);
        }}
        width={1000}
      >
        <div>
          <img
            style={{ width: "100%", height: "200px" }}
            src={dataDesc.cover}
          />
          <div className={styles.innerTitle}>影像基本信息</div>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <div>卫星：{dataDesc.satellite}</div>
            <div>传感器：{dataDesc.sensor}</div>
            <div>采集时间：2022-12-30 10:26:5</div>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <div>左上角经/纬度：117.104425/40.734503</div>
            <div>右上角经/纬度：117.373493/40.687368</div>
            <div>景中心经/纬度：</div>
          </div>
          <div className={styles.innerTitle}>系统生产参数</div>
          <div style={{ height: "100px" }}></div>
          <Button type="primary" style={{ marginBottom: "10px" }}>
            <a
              href="https://www.cpeos.org.cn/dataSearch3D/#/standardProduct"
              target="_blank"
              rel="noopener noreferrer"
            >
              文件下载
            </a>
          </Button>
          <div style={{ display: "flex" }}>
            该文件由
            <p style={{ color: "#165dff" }}>
              https://www.cpeos.org.cn/dataSearch3D/#/standardProduct
            </p>
            提供。
          </div>
        </div>
      </Modal>
      {/* 地图 */}
      <div
        style={{
          marginTop: "64px",
          width: "100%",
          height: "calc(100vh - 64px)",
        }}
        ref={mapRef}
      ></div>
    </div>
  );
}
